#!/usr/bin/env python
# encoding: utf-8

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

import configparser
import os
import time

import xlwt
import xlrd
import xlsxwriter

from ui import images

from ui.createProject import Ui_Dialog

class ProjectCreateDialog(QDialog, Ui_Dialog):
    def __init__(self, parent = None, save_path=''):
        super(QDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowIcon(QIcon(':icons/images_rc/project.png'))
        self.pushButton_open.clicked.connect(self.openDirectory)
        self.save_path = save_path
        self.proj_name = 'example'
        self.proj_path = save_path+'/'+self.proj_name
        self.lineEdit_path.setText(self.save_path)
        self.lineEdit_name.setText(self.proj_name)
        self.pushButton_getTime.clicked.connect(self.getTime)

    def openDirectory(self):
        fi = QFileDialog(self)
        fi.setWindowTitle("选择项目保存的文件夹")
        fi.setDirectory(self.save_path)
        fi.setFileMode(QFileDialog.Directory)
        if fi.exec():
            filename = fi.selectedFiles()
            if filename:
                self.lineEdit_path.setText(filename[0].replace('/','\\'))

    def getTime(self):
        _time      = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.lineEdit_time.setText(_time)

    def addProjectFile(self,path,name,operator,address,_time,remark):
        """项目信息文件

        name:     项目名称
        operator: 检测人员
        address:  检测地址
        _time:    检测时间
        """
        config = configparser.RawConfigParser()
        # 添加project选项
        config.add_section('project')
        config.set('project', 'name', name)
        config.set('project', 'operator', operator)
        config.set('project', 'address', address)
        config.set('project', 'time', _time)
        config.set('project', 'remark', remark)
        # 文件名称
        file = r'%s\%s.proj' % (path,name)
        # 写入并保存文件到当前项目文件夹下
        with open(file, 'w') as configfile:
            config.write(configfile)

    def accept(self):
        """确认创建"""
        self.proj_name = self.lineEdit_name.text()
        self.save_path = self.lineEdit_path.text()
        self.proj_path = self.save_path+'\\'+self.proj_name
        if os.path.exists(self.proj_path):
            QMessageBox.information(self,'提示','项目已存在!',QMessageBox.Yes)
        else:
            os.makedirs(self.proj_path)
            os.makedirs(self.proj_path+'\\data')
            self.addProjectFile(self.proj_path,
                                self.proj_name,
                                self.lineEdit_person.text(),
                                self.lineEdit_addr.text(),
                                self.lineEdit_time.text(),
                                self.textEdit_remark.toPlainText(),
                                )
            QDialog.accept(self)

class ProjectTreeWidget(QTreeWidget):
    signalClickTask= pyqtSignal(dict)
    signalClickProject = pyqtSignal(str)
    def __init__(self, parent = None, save_path=''):
        super(ProjectTreeWidget, self).__init__(parent)
        self.setColumnCount(1)
        self.setMinimumWidth(400)
        # 设置多选
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)
        # 取消拖拽功能
        self.setAcceptDrops(False)
        # 右键菜单设置
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.rightMenu)
        # 设置可拖拽
        # 设置显示将要被放置的位置
        # self.setDropIndicatorShown(True)
        # 设置拖放模式为移动项目，否则为复制项目
        self.setAcceptDrops(True)
        self.setDragEnabled(True)
        self.setDragDropMode(QAbstractItemView.InternalMove)
        # 拖拽功能
        self.draggedItem = None

        self.clicked.connect(self.Clicked)
        self.doubleClicked.connect(self.on_doubleClicked)

        self.projectItems = {}
        self.proj_save_path = save_path
        self.proj_name = ''

        self.save_path = save_path
        self.projects = {}
        self.createProjectDlg = ProjectCreateDialog(save_path=self.save_path)

        self.header_path = ''
        # self.clicked_path= ''
        self.selectItem = ''
        self.rootItem = ''
        self.setHeaderLabel('')
        self.icon = {
            'project':QIcon(':icons/img/project.png'),
            'data':QIcon(':icons/img/data.png')
        }

    def rightMenu(self):
        self.menu = QMenu()
        self.showProjInfoAction = QAction("&查询项目信息",triggered=self.showProjInfo)
        self.closeProjectAction = QAction("&关闭项目",triggered=self.closeProject)
        self.deleteProjectAction = QAction("&删除项目",triggered=self.deleteProject)
        self.deleteSelectsAction = QAction("&删除所选文件",triggered=self.deleteSelected)
        self.openExplorerAction= QAction("&打开文件所在位置",triggered=self.openExplorer)
        self.menu.addAction(self.showProjInfoAction)
        self.menu.addAction(self.closeProjectAction)
        self.menu.addAction(self.deleteProjectAction)
        self.menu.addAction(self.deleteSelectsAction)
        self.menu.addAction(self.openExplorerAction)
        self.menu.exec(QCursor.pos())

    def Clicked(self, item):
        self.selectItem = self.selectedItems()[0]
        # 查询根节点, 并显示当前点击目录
        rootItem = self.selectedItems()[0]
        self.header_path = rootItem.text(0)
        while rootItem.parent():
            rootItem = rootItem.parent()
            self.header_path = rootItem.text(0) +'\\' + self.header_path
        # self.clicked_path = self.save_path+'\\'+self.header_path
        # self.item_path =
        # 根目录
        self.rootItem = rootItem
        # 当前点击目录
        self.setHeaderLabel(self.header_path)
        # 项目名称
        proj_name = rootItem.text(0)
        # 更新项目路径
        self.setPath(proj_name)
        # 发送路径
        print(self.header_path)
        self.signalClickProject.emit(self.header_path)

    def dropEvent(self, event):
        droppedIndex = self.indexAt(event.pos())
        if not droppedIndex.isValid():
            return
        for dragged_item in self.selectedItems():
            # dragged_parent: 拖拽节点的父节点
            dragged_parent = dragged_item.parent()
            if dragged_parent:
                # 拖拽目的地位置对应的item
                item = self.itemAt(event.pos())
                if item:
                    item_parent = item.parent()
                    if item_parent:
                        # 获取路径
                        dragged_item_path = self.getItemPath(dragged_item)
                        item_path         = self.getItemPath(item)
                        item_parent_path  = self.getItemPath(item_parent)
                        # 同一个父节点下移动,只变化节点的顺序
                        if item_parent == dragged_parent:
                            dragged_parent.removeChild(dragged_item)
                            dragged_parent.insertChild(droppedIndex.row(), dragged_item)
                        # 不同父节点下移动节点位置，并移动节点对应的文件
                    else:
                        if item_parent.text(0) == dragged_parent.text(0):
                            # 父节点名称相同, task文件移动到task文件下, data文件移动到data文件下
                            # 移动.t文件
                            if dragged_item_path.endswith('.t'):
                                if item_path.endswith('task'):
                                    # item移动,移动文件
                                    dragged_parent.removeChild(dragged_item)
                                    item.insertChild(item.childCount(), dragged_item)
                                    if os.path.isfile(dragged_item_path) and os.path.isdir(item_path):
                                        shutil.move(dragged_item_path, item_path)
                                    if item_path.endswith('.t'):
                                        # item移动,移动文件
                                        dragged_parent.removeChild(dragged_item)
                                        item_parent.insertChild(item_parent.childCount(), dragged_item)
                                        if os.path.isfile(dragged_item_path) and os.path.isdir(item_parent_path):
                                            shutil.move(dragged_item_path, item_parent_path)
                                # 移动.d文件
                                if dragged_item_path.endswith('.d'):
                                    if item_path.endswith('data'):
                                        # item移动,移动文件
                                        dragged_parent.removeChild(dragged_item)
                                        item.insertChild(item.childCount(), dragged_item)
                                        if os.path.isfile(dragged_item_path) and os.path.isdir(item_path):
                                            shutil.move(dragged_item_path, item_path)
                                    if item_path.endswith('.d'):
                                        # item移动,移动文件
                                        dragged_parent.removeChild(dragged_item)
                                        item_parent.insertChild(item_parent.childCount(), dragged_item)
                                        if os.path.isfile(dragged_item_path) and os.path.isdir(item_parent_path):
                                            shutil.move(dragged_item_path, item_parent_path)

    def on_doubleClicked(self):
        self.showChart()
        self.showTask()

    def showChart(self):
        file_path = self.getItemPath(self.currentItem())
        if file_path:
            if os.path.isfile(file_path):
                if file_path.endswith('.d'):
                    # self.signal_showChart.emit(file_path)
                    chartDealDlg = ChartDealWidget()
                    chartDealDlg.setWindowIcon(QIcon(':icons/images_rc/chart.png'))
                    chartDealDlg.setWindowTitle(file_path)
                    # self.chartDealDlg
                    chartDealDlg.showOneLine(file_path)
                    chartDealDlg.exec()

    def showTask(self):
        """修改任务
        1、修改后生成一个新的配置文件
        2、删除修改前的文件
        3、新的配置文件就是最新修改的文件，并修改界面显示中item的名称为新配置文件的名称
        """
        print("显示任务")
        file_path = None
        if self.currentItem:
            file_path = self.getItemPath(self.currentItem())
        if file_path:
            if os.path.isfile(file_path):
                if file_path.endswith('.t'):
                    task = self.readTaskFile(file_path)
                    if task:
                        try:
                            if task['type'] == 'PDD':
                                self.pddDlg.load_config(task)
                                self.pddDlg.setWindowTitle('PDD任务显示/修改')
                                if self.pddDlg.exec() == QDialog.Accepted:
                                    conf = self.pddDlg.conf
                                    file_name = self.addTaskFile(conf)
                                    self.currentItem().setText(0, file_name)
                                    os.remove(file_path)
                            if task['type'] == 'OAR':
                                self.oarDlg.load_config(task)
                                self.oarDlg.setWindowTitle('OAR任务显示/修改')
                                if self.oarDlg.exec() == QDialog.Accepted:
                                    conf = self.oarDlg.conf
                                    # 添加新文件
                                    file_name = self.addTaskFile(conf)
                                    self.currentItem().setText(0, file_name)
                                    # 删除原文件
                                    os.remove(file_path)
                        except:
                            QMessageBox.information(self, "提示", "文件数据格式错误，无法打开", QMessageBox.Yes)
                    else:
                        QMessageBox.information(self, "提示", "文件数据格式错误，无法打开", QMessageBox.Yes)

    def readTaskFile(self, file_path=''):
        """读取任务文件中数据 """
        try:
            config = configparser.ConfigParser()
            config.read(file_path)
            condition = dict(config['condition'])
            if condition['type'] == "OAR":
                condition['road'] = json.loads(condition['road'])
                condition['pos_x'] = json.loads(condition['pos_x'])
                condition['pos_y'] = json.loads(condition['pos_y'])
                condition['step_x'] = json.loads(condition['step_x'])
                condition['step_y'] = json.loads(condition['step_y'])
            if condition['type'] == "PDD":
                condition['road'] = json.loads(condition['road'])
                condition['pos'] = json.loads(condition['pos'])
                condition['step'] = json.loads(condition['step'])
                return condition
        except:
            return False

    def openExplorer(self):
        """打开项目文件夹管理"""
        item = self.currentItem()
        if item:
            path = self.getItemPath(item)
            QProcess.startDetached('explorer.exe /select,"%s"'%(path.replace('/','\\')))

    def setPath(self,proj_name):
        # 项目保存位置
        self.save_path = r"%s\\projects"%os.getcwd()
        # 当前项目名称
        self.proj_name = proj_name
        # 当前项目路径
        self.proj_path = r"%s\\%s"%(self.save_path, self.proj_name)
        # 当前项目任务路径
        self.task_path = r"%s\\task"%self.proj_path
        # 当前项目数据路径
        self.data_path = r"%s\\data"%self.proj_path

    def getSelectsFilePath(self):
        files = []
        for s in self.selectedItems():
            files.append(self.getItemPath(s))
        return files

    def showProjInfo(self):
        try:
            rootItem = self.getRootItem(self.currentItem())
            file_path = self.projects[rootItem.text(0)]['proj_file']
            config = configparser.ConfigParser()
            config.read(file_path)
            project= config['project']
            info = \
                '项目名称：%s\r\n'%project['name']+\
                '检测人员：%s\r\n'%project['operator']+\
                '检测地点：%s\r\n'%project['address']+\
                '检测时间：%s\r\n'%project['time']+\
                '备注：\r\n%s\r\n'%project['remark']
            QMessageBox.information(self,
                                    '项目信息',
                                    info,
                                    QMessageBox.Yes)
        except:
            QMessageBox.information(self,
                                    '错误',
                                    "项目信息不存在，无法查询",
                                    QMessageBox.Yes)

    def addDataFileToCurrentItem(self, condition={},data=[]):
        """写入数据到项目文件中

        filename:文件名
        data:  测量数据 [[x,y,z,tm,ts],[x,y,z,tm,ts],....]
        condition:  测量条件 {"type":"PDD"}
        """
        config = configparser.RawConfigParser()
        # config = self.raw_config
        # 添加condition选项
        config.add_section('condition')
        _time      = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        config.set('condition', 'time', _time)
        for k in condition.keys():
            config.set('condition', str(k), str(condition[k]))
        # 添加data选项
        config.add_section('data')
        for i in range(0,len(data)):
            config.set('data', str(i), str(data[i]))
        # 文件名称
        t = condition
        ti = time.strftime("%Y%m%d%H%M%S", time.localtime())
        _hash = self.get_hashlib()
        angle = t['angle'] if 'angle' in t else ''
        half = t['half'] if 'half' in t else ''
        file_name= '%s_%s_%s_%s_%s_%s_%s_%s.d'%(
            t['ray_type'],
            t['type'],
            t['power'],
            t['ray_size_x']+'x'+t['ray_size_y'],
            t['direction'].replace('->','').replace('cm','').replace('Mev',''),
            angle,
            half,
            ti,)
        # path = r'%s\%s' % (self.data_path, file_name)
        # 保存数据文件到正在执行的item对应的项目下
        if self.currentItem():
            item = self.getRootItem(self.currentItem())
            task_path = self.projects[item.text(0)]['data_path']
            path = r'%s\%s' % (task_path, file_name)
            # 写入并保存文件到当前项目文件夹下
            with open(path, 'w') as configfile:
                config.write(configfile)
            self.addItem(file_name)
        else:
            QMessageBox.warning(self, "错误", "请选择项目再添加任务", QMessageBox.Yes)

    def newProject(self):
        """新建项目"""
        if self.createProjectDlg.exec() == QDialog.Accepted:
            path = self.createProjectDlg.proj_path
            name = self.addProject(self.createProjectDlg.proj_path)
            if name:
                self.addProjectItem(name, path)
            QMessageBox.information(self,'提示','创建项目成功!',QMessageBox.Yes)

    def openProject(self):
        """打开项目"""
        fi = QFileDialog()
        fi.setWindowTitle("打开项目")
        fi.setDirectory(self.save_path)
        fi.setFileMode(QFileDialog.DirectoryOnly)
        fi.setOption(QFileDialog.DontUseNativeDialog, True)
        file_view = fi.findChild(QListView, 'listView')
        # 设置可以打开多个文件夹
        if file_view:
            file_view.setSelectionMode(QAbstractItemView.MultiSelection)
        f_tree_view = fi.findChild(QTreeView)
        if f_tree_view:
            f_tree_view.setSelectionMode(QAbstractItemView.MultiSelection)
        if fi.exec():
            path = fi.selectedFiles()
            for p in path:
                name = self.addProject(p)
                if name:
                    self.addProjectItem(name, p)

    def closeProject(self):
        for currentItem in self.selectedItems():
            rootItem = self.getRootItem(currentItem)
            if rootItem:
                for i in range(0,self.topLevelItemCount()):
                    item = self.topLevelItem(i)
                    if item == rootItem:
                        self.takeTopLevelItem(i)
                        del self.projects[item.text(0)]
                        break
                self.header_path = ''
                self.setHeaderLabel('')
            else:
                QMessageBox.warning(self, '错误', '未选择要关闭的项目', QMessageBox.Yes)

    def closeOneProject(self, currentItem):
        rootItem = self.getRootItem(currentItem)
        if rootItem:
            for i in range(0,self.topLevelItemCount()):
                item = self.topLevelItem(i)
                if item == rootItem:
                    self.takeTopLevelItem(i)
                    del self.projects[item.text(0)]
                    break
            self.header_path = ''
            self.setHeaderLabel('')

    def deleteProject(self):
        """删除项目"""
        items = self.selectedItems()
        rootItems = [item for item in self.selectedItems() if not item.parent()]
        rootTexts = ''
        for item in rootItems:
            rootTexts = rootTexts + item.text(0)+'\r\n'
        res = QMessageBox.warning(self, '提示', '删除以下项目?:\r\n%s\r\n警告：将删除项目下的所有数据文件!!!'%rootTexts, QMessageBox.Yes|QMessageBox.No)
        if not res == 65536:
            for item in rootItems:
                path = self.getItemPath(item)
                try:
                    shutil.rmtree(path)
                    self.closeOneProject(item)
                except:
                    QMessageBox.warning(self, '提示', '项目文件已无法删除项目'%rootTexts, QMessageBox.Yes|QMessageBox.No)

    def addProject(self, path):
        """添加项目"""
        _path,name = os.path.split(path)
        if name in self.projects.keys():
            QMessageBox.warning(self, '警告', '项目已打开或已存在同名项目！！！', QMessageBox.Yes)
        else:
            list_file = os.listdir(path)
            data_dir = None
            point_proj_file = None
            for file in list_file:
                if file == 'data':
                    if os.path.isdir(os.path.join(path, file)):
                        data_dir=r'%s'%os.path.join(path, file)
                if file == '%s.proj'%name:
                    if os.path.isfile(os.path.join(path, file)):
                        point_proj_file =r'%s'%os.path.join(path, file)
            if data_dir and point_proj_file:
                self.projects[name] = {
                    'path':path,
                    'data_path':data_dir,
                    'proj_file':point_proj_file,
                }
                return name

    def addProjectItem(self, proj_name='',proj_path=''):
        """添加一个总项目"""
        if proj_name in self.projectItems.keys():
            QMessageBox.information(self,'提示','项目已打开',QMessageBox.Yes)
            return
        item = QTreeWidgetItem([proj_name])
        item.setIcon(0,self.icon['project'])
        file_list = os.listdir(proj_path)
        for f in file_list:
            if f=='data':
                data_item = QTreeWidgetItem([f])
                data_item.setIcon(0,self.icon['data'])
                item.addChild(data_item)
                data_file_list = os.listdir(proj_path+'/'+'data')
                for f in data_file_list:
                    if f.endswith('.xls'):
                        _item = QTreeWidgetItem([f])
                        _item.setIcon(0,self.icon['data'])
                        data_item.addChild(_item)
        self.setHeaderLabel(proj_name)
        self.addTopLevelItem(item)
        self.setPath(proj_name)

    def getRootItem(self, item):
        rootItem = item
        while rootItem.parent():
            rootItem = rootItem.parent()
        return rootItem

    def deleteSelected(self):
        '''删除选中'''
        file_list = [item.text(0) for item in self.selectedItems()]
        if not QMessageBox.warning(self,'删除确认','确认要删除以下文件么？\r\n%s'%('\r\n'.join(file_list)),QMessageBox.Yes|QMessageBox.No) == 65536:
            for item in self.selectedItems():
                item_parent = item.parent()
                if item.text(0).endswith('.xls'):
                    item.parent().removeChild(item)
                    # 删除文件
                    file_path = self.proj_save_path+'/'+item_parent.parent().text(0)+'/'+item_parent.text(0)+'/'+item.text(0)
                    try:
                        os.remove(file_path)
                    except:
                        QMessageBox.warning(self,'提示','删除失败：文件已打开或文件已删除',QMessageBox.Yes)
                else:
                    QMessageBox.warning(self,'提示','请选择以.xls文件结尾的数据',QMessageBox.Yes)

    def addItem(self,file_name):
        if self.rootItem:
            for i in range(0,self.rootItem.childCount()):
                _type = ''
                if file_name.endswith('.xls'):
                    _type = 'data'
                if self.rootItem.child(i).text(0)==_type:
                    it = QTreeWidgetItem([file_name])
                    it.setIcon(0,self.icon[_type])
                    self.rootItem.child(i).addChild(it)

    def getItemPath(self, item):
        """获取任务文件的路径"""
        if item:
            if item.parent():
                rootItem = item
                item_path = rootItem.text(0)
                while rootItem.parent():
                    rootItem = rootItem.parent()
                    item_path = rootItem.text(0) +'/' + item_path
                item_path = self.projects[rootItem.text(0)]['path']+'/'+item_path.replace(rootItem.text(0)+'/','')
                return item_path
            else:
                rootItem = item
                item_path = self.projects[rootItem.text(0)]['path']
                return item_path

    def addDataFile(self, conf):
        ti = time.strftime("%Y%m%d%H%M%S", time.localtime())
        type = conf['type']
        file_name = '%s_%s.xls'%( type, ti)
        if self.currentItem():
            item = self.rootItem
            data_path = self.projects[item.text(0)]['data_path']
            path = r'%s\%s' % (data_path, file_name)
            path = path.replace('\\','/')
            # 写入并保存文件到当前项目文件夹下
            # try:
            wb = xlsxwriter.Workbook(path)
            ws = wb.add_worksheet()
            if type == '辐射角':
                ws.write(0, 0, "辐射角测量数据结果")
                ws.write(1, 0, "x(mm)")
                ws.write(1, 1, "T1")
                ws.write(1, 2, "T2")
                data = conf['data']
                if data:
                    for i in range(0, len(data)):
                        for j in range(0, len(data[i])):
                            ws.write(i+2, j, str(data[i][j]))
                ws.write(1,4,"左边辐射角")
                ws.write(1,5,conf["angle_left"])
                ws.write(2,4,"右边辐射角")
                ws.write(2,5,conf["angle_right"])
                ws.write(3,4,"辐射角")
                ws.write(3,5,conf["angle"])
                ws.write(4,4,"最大剂量位置")
                ws.write(4,5,conf["max_dose_pos"])
                ws.write(5,4,"左边50%剂量位置")
                ws.write(5,5,conf["half_dose_left_pos"])
                ws.write(6,4,"右边50%剂量位置")
                ws.write(6,5,conf["half_dose_right_pos"])
                ws.insert_image("H1",conf["result_image_path"])
                ws.insert_image("H21",conf["data_image_path"])
            if type == '空气比释动能':
                ws.write(0, 0, "空气比释动能测量结果")
                ws.write(1, 0, "时间(s)")
                ws.write(1, 1, "主测通道剂量率(cGy/min)")
                ws.write(1, 2, "主测通道累积剂量(cGy)")
                data = conf['data']
                if data:
                    for i in range(0, len(data)):
                        for j in range(0, len(data[i])):
                            ws.write(i+2, j, str(data[i][j]))
                ws.write(1,4,"射线能量(kV)")
                ws.write(1,5,conf["power"])
                ws.write(2,4,"校准因子")
                ws.write(2,5,conf["calibrationFactor"])
                ws.write(3,4,"气压(kPa)")
                ws.write(3,5,conf["airPressure"])
                ws.write(4,4,"温度(℃ )")
                ws.write(4,5,conf["temperature"])
                ws.write(5,4,"空气比释动能")
                ws.write(5,5,conf["airKerma"])
                ws.write(6,4,"主测通道重复性")
                ws.write(6,5,conf["master_repeat"])
            if type == '重复性':
                ws.write(0, 0, "重复性测量结果")
                ws.write(1, 0, "时间(s)")
                ws.write(1, 1, "主测通道累积剂量(cGy)")
                data = conf['data']
                if data:
                    for i in range(0, len(data)):
                        for j in range(0, len(data[i])):
                            ws.write(i+2, j, str(data[i][j]))
            if type == '漏射线':
                ws.write(0, 0, "漏射线测量结果")
                ws.write(1, 0, "监测通道剂量率(mGy/h)")
                ws.write(1, 1, "监测通道累积剂量(mGy/h)")
                ws.write(1,4,"监测通道剂量率(平均值)")
                ws.write(1,5,conf["tunnel_2_rate_avg"])
                data = conf['data']
                if data:
                    for i in range(0, len(data)):
                        for j in range(0, len(data[i])):
                            ws.write(i+2, j, str(data[i][j]))
            wb.close()
            QMessageBox.warning(self, '提示', '导出成功!\r\n%s' % path, QMessageBox.Yes)
            # except:
                # QMessageBox.warning(self, '提示', '导出失败!\r\n文档已打开，请关闭文档后再试！', QMessageBox.Yes)

            self.addItem(file_name)
        else:
            QMessageBox.warning(self, "错误", "请选择项目再添加任务", QMessageBox.Yes)
        return

